import cv2,math
import numpy as np

d=float(input('请输入检测圆直径(cm)\n'))
A=30171.8558*((d/2)/1.7)**2 #30171.8558为标定物在15cm处的面积，1.7为标定物半径（cm)
camera = cv2.VideoCapture(0)
while True:
    ret, frame = camera.read()
    if ret == True:
        gray = cv2.GaussianBlur(frame, (21, 21), 0)
        gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
        
        circles1 = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,
        630,param1=100,param2=50,minRadius=5,maxRadius=230)
        try :
            circles = circles1[0,:,:]#提取为二维
            circles = np.float32(np.around(circles))#四舍五入，取整
            for i in circles[:]: 
                cv2.circle(gray,(i[0],i[1]),i[2],(255,0,0),5)#画圆
                cv2.circle(gray,(i[0],i[1]),2,(255,0,255),10)#画圆心
                dis=math.pi*int(i[2])**2
                print('圆心坐标为：',i[0],i[1],'半径为',i[2],'面积为',dis)
                print('距离',15*math.sqrt(A/dis),'厘米')
            cv2.imshow('image',gray)
        except:
            pass
        cv2.imshow('gray',frame)
    key=cv2.waitKey(1)
    if(key == ord('q')):
         break
camera.release()
cv2.destroyAllWindows()


